package com.bidevalution.controller.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.bidevalution.business.service.BeSectionEnterpriseService;
import com.bidevalution.core.enums.FileStatusEnum;
import com.bidevalution.support.context.Constants;
import com.qtp.core.util.OConvertUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bidevalution.business.service.BeBidFileService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.controller.task.SectionStepDataTask;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.dao.entity.BeBidFile;
import com.bidevalution.dao.entity.BeSectionEnterprise;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.service.EntInfoService;
import com.bidevalution.support.util.LogUtil;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/beBidFile")
@Api(tags = "招投标文件上传")
public class BeBidFileController extends BaseController {
	private LogUtil log = LogUtil.getLogManager(getClass());
	@Autowired
	private BeBidFileService beBidFileService;
	@Autowired
	private EnterPriseInfoDubboService enterPriseInfoDubboService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Autowired
	private EntInfoService entInfoService;
	@Autowired
	private BeSectionEnterpriseService enterpriseService;

	private static final String FAIL_MESSAGE_TAG = "QzMsg:";
	private static final String DEFAULT_ERROR_MSG = "文件解析失败，请联系管理员查询后端错误信息。";
	


	/**
	 * 保存上传文件信息
	 * @param fileId
	 * @param status
	 * @param fileName
	 * @return
	 */
	@PostMapping("/save")
	@ApiOperation(value = "保存上传结果", response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "fileId", value = "文件Id", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "fileType", value = "1招标文件 2投标文件", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "fileName", value = "文件名称", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "sectionId", value = "招标标段ID", dataType = "String", paramType = "query")})
	public Response<String> saveRecord(@RequestParam("fileId") String fileId,@RequestParam("fileName") String fileName,@RequestParam("fileType") String fileType,
									   @RequestParam(name = "sectionId", required = false)String sectionId) {
		try {
			String userGuid = RequestUtil.getHeader("userGuid");
			TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
			BeBidFile beBidFile = new BeBidFile();
			beBidFile.setCreateTime(new Date());
			beBidFile.setFileId(fileId);
			beBidFile.setModifyTime(new Date());
			beBidFile.setFileType(fileType);
			beBidFile.setParentId(fileType);
			beBidFile.setSectionId(sectionId);
			beBidFile.setOrgId(tsUser.getOrgId());
			beBidFile.setFileName("上传中");
			String orgCode = "";
			Map<String, Object> params = new HashMap<>();
			params.put("ep_guid", tsUser.getOrgId());
			// 获取请求中的参数
			try {
				Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(params);
				if (response.getResult() != null) {
					orgCode = String.valueOf(response.getResult().get("ep_org_code"));
				}
				log.info("response:"+response.getResult());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			beBidFile.setOrgCode(orgCode);
			beBidFile.setStatus("1");
			beBidFile.setFileName(fileName);
			beBidFileService.insertSelective(beBidFile);
			return Response.ok();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Response.fail(e.getMessage());
		}
	}

	/**
	 * 招标文件查询列表
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@GetMapping("/zbList")
	@ApiOperation(value = "招标文件查询列表", response = BeSectionInfo.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "startDate", value = "文件名称", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "endDate", value = "文件名称", required = true, dataType = "String", paramType = "query")})
	public Response<List<BeSectionInfo>> selectByOrgId(@RequestParam("startDate")String startDate,@RequestParam("endDate")String endDate) {
		String userGuid = RequestUtil.getHeader("userGuid");
		TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
		String orgCode = "";
		if(tsUser == null || StringUtils.isEmpty(tsUser.getOrgId())){
			return Response.fail("用户orgId为空！");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("ep_guid", tsUser.getOrgId());
		// 获取请求中的参数
		Response<Map<String, Object>> response;
		try {
			response = enterPriseInfoDubboService.getEnterInfo(params);
			if (response.getResult() != null) {
				orgCode = String.valueOf(response.getResult().get("ep_org_code"));
			}
			log.info("response:"+response.getResult());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return Response.fail("系统错误，请联系管理员！");
		}
		return Response.ok(beBidFileService.selectByOrgCode(orgCode,startDate,endDate));
	}
	/**
	 * 招标文件查询列表
	 * 
	 * @param sectionId 标段Id
	 * @return
	 */
	@GetMapping("/tbList")
	@ApiOperation(value = "招标文件查询列表", response = BeSectionEnterprise.class)
	@ApiImplicitParams({@ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "enterpriseName", value = "企业名称", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "password", value = "密码", required = false, dataType = "String", paramType = "query") })
	public Response<List<BeSectionEnterprise>> saveRecord(HttpServletRequest request
			, @RequestParam(name="enterpriseName",required = false) String enterpriseName, @RequestParam("sectionId") String sectionId
			, @RequestParam(name="password",required = false) String password) {
		String userGuid = request.getHeader("userGuid");
		TSUser user = RedisAccess.getValue(TSUser.class, userGuid);
		String userLoginName = null;
		if(user!=null) {
			userLoginName = user.getLoginName();
		}
		log.info("获取投标列表，参数：sectionId="+sectionId+",password="+password+",userName="+userLoginName+",user="+user+",userGuid="+userGuid);
		return beBidFileService.selectBySectionId(sectionId, enterpriseName, userLoginName, password);
	}

	@GetMapping("/getImportEntInfo")
	@ApiOperation(value = "获取导入的单位核对信息", response = BeSectionEnterprise.class)
	@ApiImplicitParams({@ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "fileId", value = "上传的文件id", required = true, dataType = "String", paramType = "query") })
	public Response<BeSectionEnterprise> getImportEntInfo(@RequestParam("sectionId") String sectionId, @RequestParam("fileId") String fileId) {
		BeBidFile bidFile = beBidFileService.selectByPrimaryKey(fileId);
		if(bidFile != null) {
			String ptEntGuid = bidFile.getBidEntId();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(ptEntGuid)) {
				BeSectionEnterprise enterprise = enterpriseService.getEnterpriseByPtId(ptEntGuid);
				if(enterprise != null) {
					return Response.ok(enterprise);
				}
			}
		}
		return Response.ok();
	}
	/**
	 * 保存上传文件信息
	 * 
	 * @param sectionId 标段Id
	 * @return
	 */
	@GetMapping("/getFileId")
	@ApiOperation(value = "获取上传文件fileid", response = String.class)
	public Response<String> getFileId() {

		return Response.ok(UUID.randomUUID().toString());
	}
	/**
	 * 获取上传文件状态
	 * 
	 * @param fileId 文件id
	 * @return
	 */
	@GetMapping("/getBidFileStatus")
	@ApiOperation(value = "获取上传文件状态", response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "fileId", value = "文件ID", required = true, dataType = "String", paramType = "query")})
	public Response<String> getBidFileStatus(@RequestParam("fileId") String fileId) {

		BeBidFile beBidFile = beBidFileService.selectByPrimaryKey(fileId);
		if(beBidFile == null) {
			return Response.fail("文件不存在");
		}
		//获取失败原因，如果是java报错，那就不提示
		String memo = beBidFile.getMemo();
		int status = OConvertUtils.getInt(beBidFile.getStatus(), 0);
		if(FileStatusEnum.PARSE_FAIL.getStatus() == status) {
			String[] str = memo.split("\n");
			if (!StringUtils.isEmpty(memo) && str[0].contains(FAIL_MESSAGE_TAG)) {
				memo = str[0].substring(str[0].indexOf(FAIL_MESSAGE_TAG)+FAIL_MESSAGE_TAG.length());
			} else {
				memo = DEFAULT_ERROR_MSG + "\n错误ID："+fileId;
			}
			memo = memo.trim();
		}
		//添加解析成功立即触发招标文件同步
//		if("1".equals(beBidFile.getFileType()) && status==3) {
//			BeSectionInfo beSectionInfo = beSectionInfoService.selectByCode(beBidFile.getProjCode());
//			if(beSectionInfo != null) {
//				sectionStepDataTask.synData(beSectionInfo);
//			}
//		}
		//先设置失败原因，再设置状态
		Response<String> rsp = Response.fail(memo);
		rsp.setResult(beBidFile.getStatus());
		rsp.setStatus(HttpStatus.SC_OK);
		return rsp;
	}
	/**
	 * 保存上传文件信息
	 * 
	 * @param sectionId 标段Id
	 * @return
	 */
	@GetMapping("/pushData")
	@ApiOperation(value = "推送数据", response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query")})
	public Response<String> pushData(@RequestParam("sectionId") String sectionId) {
		try {
			BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
			if(beSectionInfo == null ||StringUtils.isEmpty(beSectionInfo.getSectionCode())) {
				return Response.fail("操作失败,不存在标段数据");	
			}
			Response<String> response = entInfoService.getProjectBLUpdate(beSectionInfo.getSectionCode());
			log.info("response:"+response.getResult());
			if(response.isSuccess()) {
				return Response.ok("操作成功");
			}else {
				return Response.fail("操作失败");
			}
		}catch (Exception e) {
			log.error(e.getMessage(),e);
			return Response.fail("操作失败");
		}
	}

	@GetMapping("/findErrorBidFileList")
	@ApiOperation(value = "推送数据", response = String.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "date", value = "查询日期", required = true, dataType = "String", paramType = "query")})
	public Response<List<BeBidFile>> findErrorBidFileList(@RequestParam("date") String date) {
		return Response.ok(beBidFileService.findErrorBidFileList(date, date));
	}
}
